package com.sgu6.sgu6_machine.ui.dialog;

import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.sgu6.middleware.util.HexUtil;
import com.sgu6.serialport.manager.SerialPortManagerForCard;
import com.sgu6.sgu6_machine.R;
import com.sgu6.sgu6_machine.container.MachineContainer;
import com.sgu6.sgu6_machine.dto.CreateMemberCardDto;
import com.sgu6.sgu6_machine.dto.CreateMemberCardParams;
import com.sgu6.sgu6_machine.event.ReadCardEvent;
import com.sgu6.sgu6_machine.presenter.MachineP;
import com.sgu6.sgu6_machine.ui.MainA;
import com.sgu6.sgu6_machine.ui.dialog.proxy.ProxyDialogFragment;
import com.sgu6.sgu6_machine.util.ToastUtil;
import com.wang.avi.AVLoadingIndicatorView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class EnableCardDialogF extends ProxyDialogFragment {

    @BindView(R.id.label)
    TextView label;
    @BindView(R.id.et_card)
    EditText etCard;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.btnEnable)
    TextView btnEnable;
    @BindView(R.id.loading)
    AVLoadingIndicatorView loading;

    private CountDownTimer timer;
    private String phone = "", sgu6Code = "",cardNo="";
    private MachineP mp = new MachineP();
    private Timer cmdTimer = new Timer();
    private TimerTask task;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        View v = inflater.inflate(R.layout.dialog_fragment_enable_card, container, false);
        unbinder = ButterKnife.bind(this, v);

        initUI();

        return v;
    }

    private void initUI() {
        timer = new CountDownTimer(60 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                int second = (int) (millisUntilFinished / 1000);
            }

            @Override
            public void onFinish() {
                timer.cancel();
                dismiss();
            }
        }.start();
    }


    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        Dialog dialog = getDialog();
        if (dialog != null) {
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            dialog.getWindow().setLayout((int) (dm.widthPixels * 0.5), ViewGroup.LayoutParams.WRAP_CONTENT);
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (timer != null) {
                        timer.cancel();
                        timer = null;
                    }
                    onDestroy();
                    onDestroyView();
                    onDetach();
                    Runtime.getRuntime().gc();
                }
            });
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    @OnClick({R.id.et_phone, R.id.btnEnable})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.et_phone:
                break;
            case R.id.btnEnable:
                btnEnable.setClickable(false);
                phone = etPhone.getText().toString();
                cardNo = etCard.getText().toString();
                if (cardNo.length()==8){
                    if (phone.length() == 11) {
                        loading.setVisibility(View.VISIBLE);
                        task = new TimerTask() {
                            @Override
                            public void run() {
                                SerialPortManagerForCard.getInstance().sendBytes(HexUtil.HexString2Bytes("AA080400FFFFFFFFFFFF"));
                            }
                        };
                        cmdTimer.schedule(task, 500, 1000);
                    } else {
                        ToastUtil.showLongToast(requireContext(), "手机号格式错误");
                    }
                }else {
                    ToastUtil.showLongToast(requireContext(), "卡号格式错误");
                }

                break;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReadCardEvent(ReadCardEvent event) {
        //发送读卡指令
        //SerialPortManagerForCard.getInstance().sendBytes(HexUtil.HexString2Bytes("AA 08 04 01 FF FF FF FF FF FF"));

        if (event.cmd.startsWith("AA120400")) {
            task.cancel();
            sgu6Code = event.cmd.substring(8);
            mp.createMemberCard(new CreateMemberCardParams(sgu6Code, cardNo, MachineContainer.machineConfigDto.merchantId, 0, 1, phone));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCreateMemberCardEvent(CreateMemberCardDto dto) {
        loading.setVisibility(View.GONE);
        if (dto.isSucceed()) {
            Log.i(TAG, "onCreateMemberCardEvent: 会员卡创建成功");
            SerialPortManagerForCard.getInstance().sendBytes(HexUtil.HexString2Bytes("AA03B20501"));
            ToastUtil.showShortToast(requireContext(), "会员卡注册成功");
        } else {
            ToastUtil.showShortToast(requireContext(), "注册失败，请重新注册！" + dto.getErrMsg());
            SerialPortManagerForCard.getInstance().sendBytes(HexUtil.HexString2Bytes("AA03B20501"));
        }
        dismiss();
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        if (task != null) {
            task.cancel();
            task = null;
        }
    }
}
